﻿using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Windows;
using System;

public partial class MainWindow : Window
{
    // 智谱清言API v4 配置
    private readonly string apiKey = "3ab401aa80814abd82f4bfae22e841fb.kHLZvyXJARjoi37G";
    private readonly string textApiEndpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    private readonly string imageApiEndpoint = "https://open.bigmodel.cn/api/paas/v4/images/generations";
    private readonly string modelName = "glm-4-flash-250414";
    private readonly string imageModelName = "cogview-4-250304";

    // 数据收集
    private List<WordItem> wordList;
    private ObservableCollection<WordItem> mistakeList;
    private int currentLearnIndex = 0;

    // 文件路径（不用于加载，仅当重新启用会话期间保存时）
    // 对于"总是全新开始"模式，这些主要供参考，或者如果有选择地重新启用保存
    private readonly string wordsDataFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "words.json");
    private readonly string mistakesDataFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mistakes.json");

    // 工具类
    private readonly HttpClient httpClient;
    private Random random = new Random();

    // 测试模式状态
    private WordItem currentTestWord;
    private int correctAnswers = 0;
    private int totalQuestionsAnswered = 0;

    // 注意：UI元素字段（如loadingIndicatorPopup）是从XAML x:Name自动生成的
    // 这里没有显式的C#字段声明

    public MainWindow()
    {
        InitializeComponent(); // 初始化XAML组件，使x:Name命名的元素可用

        if (apiKey == "YOUR_API_KEY" || apiKey.Length < 10)
        {
            MessageBox.Show("请在 MainWindow.xaml.cs 文件中设置有效的智谱AI API密钥。", "API密钥未设置", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.Timeout = TimeSpan.FromSeconds(60);

        InitializeLoadingPopup(); // 验证XAML定义的加载UI元素

        wordList = new List<WordItem>();
        mistakeList = new ObservableCollection<WordItem>();
        Console.WriteLine("[数据策略] 以全新状态启动，不加载先前数据。");

        lvWrongWords.ItemsSource = mistakeList;
        UpdateMistakeListControls();
        UpdateWordCountStatus();
        ClearLearnWordDisplay(); // 设置学习标签页的初始空状态
        SetLearnControlsEnabled(false); // 禁用依赖单词的控件
        btnNewWord.IsEnabled = true; // 新单词按钮应该可用

        this.Loaded += MainWindow_Loaded;
    }

    private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        this.Loaded -= MainWindow_Loaded; // 防止重复进入

        if (!wordList.Any()) // 只有当没有单词时才生成（例如应用刚启动时）
        {
            UpdateStatus("正在准备第一个单词...");
            await GenerateNewWordAndDisplay();
        }

        // 尝试生成第一个单词后更新状态
        if (wordList.Any() && currentLearnIndex >= 0 && currentLearnIndex < wordList.Count)
        {
            // DisplayCurrentLearnWord会更新状态，但我们可以根据需要设置一个通用的"准备就绪"状态
            UpdateStatus($"准备就绪. 当前单词: {wordList[currentLearnIndex].Word}");
        }
        else if (!wordList.Any()) // 如果生成失败且列表仍然为空
        {
            UpdateStatus("无法自动生成首个单词。请手动点击"新单词"");
        }
    }

    public class WordItem
    {
        public string Word { get; set; }
        public string Phonetic { get; set; }
        public string ChineseDefinition { get; set; }
        public string Example { get; set; }
        public string ImageUrl { get; set; }
        public DateTime LearningDate { get; set; }
        public bool IsKnown { get; set; } = false;
        public int TimesIncorrect { get; set; } = 0;

        [JsonIgnore] public string WordText => Word;
        [JsonIgnore] public string Definition => ChineseDefinition; // 为了XAML绑定一致性，如果使用"Definition"
    }

    public class WordInfoFromApi
    {
        [JsonPropertyName("word")] public string Word { get; set; }
        [JsonPropertyName("phonetic")] public string Phonetic { get; set; }
        [JsonPropertyName("chineseDefinition")] public string ChineseDefinition { get; set; }
        [JsonPropertyName("example")] public string Example { get; set; }
        [JsonPropertyName("imageDescription")] public string ImageDescription { get; set; }
    }

    #region --- 学习模式 ---
    private void DisplayCurrentLearnWord()
    {
        if (wordList.Count == 0 || currentLearnIndex < 0 || currentLearnIndex >= wordList.Count)
        {
            ClearLearnWordDisplay();
            SetLearnControlsEnabled(false);
            btnNewWord.IsEnabled = true;
            UpdateStatus("词库中没有单词。请生成新单词。");
            return;
        }

        var word = wordList[currentLearnIndex];
        txtWord.Text = word.Word;
        txtPhonetic.Text = word.Phonetic;
        txtChineseDefinition.Text = $"释义: {word.ChineseDefinition}"; // 使用标签提高清晰度
        txtExample.Text = $"例句: {word.Example}";
        txtChineseDefinition.Visibility = Visibility.Visible; // 确保可见

        LoadImage(word.ImageUrl, imgWord, txtImageLoading);

        btnMarkKnown.Content = word.IsKnown ? "标记未掌握" : "我会了";
        SetLearnControlsEnabled(true); // 启用依赖单词的控件
        btnNewWord.IsEnabled = true;   // 新单词按钮应保持启用

        UpdateStatus($"学习: {word.Word} ({currentLearnIndex + 1}/{wordList.Count})");
    }

    private void ClearLearnWordDisplay()
    {
        txtWord.Text = "Word";
        txtPhonetic.Text = "[Phonetic]";
        txtChineseDefinition.Text = "释义将在此显示...";
        txtChineseDefinition.Visibility = Visibility.Visible;
        txtExample.Text = "例句将在此显示...";
        // 设置默认或主题化的占位图像
        imgWord.Source = new BitmapImage(new Uri("https://picsum.photos/700/200?grayscale&blur=2&random=" + Guid.NewGuid().ToString()));
    }

    private void SetLearnControlsEnabled(bool enableWordDependentControls)
    {
        // btnNewWord单独处理（通常总是启用，除非操作正在进行中）
        btnPrevious.IsEnabled = enableWordDependentControls && wordList.Count > 1;
        btnNext.IsEnabled = enableWordDependentControls && wordList.Count > 1;
        btnMarkKnown.IsEnabled = enableWordDependentControls;
        btnAddToMistakes.IsEnabled = enableWordDependentControls;
    }

    private async Task GenerateNewWordAndDisplay()
    {
        ShowLoading("正在生成新单词...");
        btnNewWord.IsEnabled = false;
        SetLearnControlsEnabled(false);
        try
        {
            WordItem newWordItem = null;
            int attempts = 0;
            const int maxAttempts = 3; // 获取唯一单词的最大尝试次数

            while (attempts < maxAttempts)
            {
                attempts++;
                UpdateLoadingMessage($"获取新单词 (尝试 {attempts}/{maxAttempts})...");
                var candidateWord = await GetWordFromZhipu(); // API/解析错误时返回null
                if (candidateWord != null)
                {
                    if (!wordList.Any(w => w.Word.Equals(candidateWord.Word, StringComparison.OrdinalIgnoreCase)))
                    {
                        newWordItem = candidateWord;
                        break; // 找到唯一单词
                    }
                    else
                    {
                        Console.WriteLine($"[生成重复单词] 单词 '{candidateWord.Word}' 已存在，尝试重新生成。");
                    }
                }
                else
                {
                    // GetWordFromZhipu返回null（错误已由其显示）。停止尝试。
                    break;
                }
                if (attempts < maxAttempts) await Task.Delay(TimeSpan.FromMilliseconds(600)); // 重试前暂停
            }

            if (newWordItem != null)
            {
                wordList.Add(newWordItem);
                currentLearnIndex = wordList.Count - 1;
                DisplayCurrentLearnWord(); // 更新UI和状态
                UpdateWordCountStatus();
            }
            else if (attempts >= maxAttempts) // 未能获取唯一单词
            {
                ShowError("生成单词失败", $"尝试 {maxAttempts} 次后未能获取到新的、不重复的单词。请稍后再试。");
                UpdateStatus("未能生成不重复的新单词。");
                if (!wordList.Any()) ClearLearnWordDisplay(); // 如果列表仍然为空则清除
            }
            else // newWordItem为null，但attempts < maxAttempts（意味着API错误）
            {
                UpdateStatus("生成新单词失败，请查看错误提示。");
                if (!wordList.Any()) ClearLearnWordDisplay();
            }
        }
        catch (Exception ex) // 捕获任何意外错误
        {
            Console.WriteLine($"[GenerateNewWordAndDisplay Error] {ex}");
            ShowError("生成单词严重错误", $"处理新单词时发生意外: {ex.Message}");
            UpdateStatus("生成新单词时出错。");
            if (!wordList.Any()) ClearLearnWordDisplay();
        }
        finally
        {
            HideLoading();
            btnNewWord.IsEnabled = true; // 总是重新启用NewWord按钮
            SetLearnControlsEnabled(wordList.Any()); // 重新评估其他控件
        }
    }

    private void BtnPrevious_Click(object sender, RoutedEventArgs e)
    {
        if (wordList.Count > 0)
        {
            currentLearnIndex = (currentLearnIndex - 1 + wordList.Count) % wordList.Count;
            DisplayCurrentLearnWord();
        }
    }

    private void BtnNext_Click(object sender, RoutedEventArgs e)
    {
        if (wordList.Count > 0)
        {
            currentLearnIndex = (currentLearnIndex + 1) % wordList.Count;
            DisplayCurrentLearnWord();
        }
    }

    private void BtnNewWord_Click(object sender, RoutedEventArgs e)
    {
        _ = GenerateNewWordAndDisplay(); // 异步调用，不等待结果
    }

    private void BtnMarkKnown_Click(object sender, RoutedEventArgs e)
    {
        if (wordList.Count == 0 || currentLearnIndex < 0 || currentLearnIndex >= wordList.Count) return;
        var word = wordList[currentLearnIndex];
        word.IsKnown = !word.IsKnown;
        btnMarkKnown.Content = word.IsKnown ? "标记未掌握" : "我会了"; // 更新按钮文本
        // 你可能也想更改图标，例如未掌握时使用空心星Tag=""
        UpdateStatus($"单词 '{word.Word}' 已标记为 {(word.IsKnown ? "已掌握" : "未掌握")}");
        UpdateWordCountStatus();
    }

    private void BtnAddToMistakes_Click(object sender, RoutedEventArgs e)
    {
        if (wordList.Count == 0 || currentLearnIndex < 0 || currentLearnIndex >= wordList.Count) return;
        AddWordToMistakes(wordList[currentLearnIndex]);
    }
    #endregion
}